<?php


namespace app\common\cachemodel\zlcr2;


use app\common\model\BaseCache;
use think\Cache;
use think\Log;
use XznsTools\cache\CacheManage;

class Zlcr2AstrTasks extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr2_astr_tasks';

    protected $cacheModel = 'question_answer.astr_task';

    /**
     * 新增 接单记录
     * @param int $astrId
     * @param $data
     * @return bool
     */
    public function SaveData(int $astrId, $data)
    {
        try
        {
            $id = $this->insertGetId($data);
            // 添加至 进行中任务
            $this->listDataAdd($astrId, [$id => $data['create_time']], 1);    // 缓存以咨询ID为key type=1 进行中 0=>全部结束任务 2=>已完成
            Cache::set('question_answer:is_underway:' . $astrId, 1, 86400); // 记录占星师当前有进行中的任务

            return $id;
        }
        catch (\Exception $e)
        {
            Log::write('问答 Zlcr2AstrTasks model => SaveData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return 0;
        }
    }

    /**
     * 更新 接单记录
     * @param int $id
     * @param int $astrId
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $id, int $astrId, array $data)
    {
        try
        {
            $this->where(['id' => $id])->update($data);

            if (isset($data['status']))
            {
                if ($data['status'] === 2)
                {
                    $this->listDataAdd($astrId, [$id => $data['update_time']], 2);    // 缓存以咨询ID为key type=1 进行中 0=>全部结束任务 2=>已完成
                }
                if (in_array($data['status'], [3, 5, 6, 7], true))
                {   // 状态 1=>进行中 2=>已完成 3=>已弃答 4=>用户申述已取消 5=>答案回复超时 6追问回复超时未完成 7=>抽查被扣除收益
                    if ($data['status'] === 3)
                    {
                        $this->listDataAdd($astrId, [$id => $data['update_time']], 3);    // 缓存以咨询ID为key type=3 已弃答
                    }
                    $this->listDataDel($astrId, [$id], 1);

                    if (in_array($data['status'], [3, 5], true))
                    {
                        Cache::rm('question_answer:is_underway:' . $astrId); // 移除进行中的任务
                    }
                }
                // 进行中删除
                $this->listDataDel($astrId, [$id], 1);
            }

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data);

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('问答 Zlcr2AstrTasks model => UpdateData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $model = $this->where('id', 'in', $ids);
            } else
            {
                $model = $this->where(['astr_id' => $type[0], 'status' => $type[1]]);

                if ($type[1] == 2)
                {
                    $model = $model->limit(20);
                }
            }

            $data = $model
                ->order('id', 'DESC')
                ->column('id,qid,astr_id,qa_level,question_type,status,create_time,update_time,earning,lock_earning', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        foreach ($resData as $orderId => $questionItemData)
        {
            $resData[$orderId] = arrayKeyData2int($questionItemData, ['id', 'astr_id', 'qa_level', 'question_type', 'status', 'create_time', 'update_time', 'lock_earning']);
        }

        return $resData;
    }

    /**
     * 获取24小时内弃答的qids
     * @param int $astrId
     * @return array
     * @throws \Exception
     */
    public function getDiscardQids(int $astrId)
    {
        $cacheModel = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $astrId)->setListKeyType(3);// 类型 type=3 已弃答
        $redis = $cacheModel->redisHandler;
        $time = time();
        if ($redis->exists($cacheModel->cacheKey['list']))
        {   // 缓存存在
            $taskIds = $redis->zRangeByScore($cacheModel->cacheKey['list'], $time - 259200, $time);
        } else
        {   // 缓存丢失
            $questionData = $this->where(['status' => 3, 'astr_id' => $astrId, 'update_time' => ['>', $time - 259200]])->column('update_time', 'id');
            $pipe = $redis->multi($redis::PIPELINE);
            $pipe->zAdd($cacheModel->cacheKey['list'], [], 0, 0);
            $taskIds = [];
            foreach ($questionData as $taskId => $updateTime)
            {
                $pipe->zAdd($cacheModel->cacheKey['list'], [], $updateTime, $taskId);
                $taskIds[] = $taskId;
            }
            $pipe->exec();
            $redis->expire($cacheModel->cacheKey['list'], 86400);  // 1天过期时间
        }

        $qids = $this->batchGetInfoByIds($taskIds, ['qid']);

        return $qids ? array_column($qids, 'qid') : [];
    }

    /**
     * 获取占星师今日弃答次数
     * @param int $astrId
     * @return int
     * @throws \Exception
     */
    public function getAstrDiscardQuestionNumByToday(int $astrId): int
    {
        $qids = $this->getDiscardQids($astrId);

        return count($qids);
    }

    /**
     * 获取 问答咨询师 能解答的问题商品ID
     * @param array $astrInfo
     * @return array
     */
    public function getAstrAnswerGids(array $astrInfo)
    {
        $goodInfo = config('zlcr2_question.info');
        $gids = [];
        foreach ($goodInfo as $gid => $item)
        {
            switch ($item['type'])
            {
                case 1: // 看盘
                    if ($astrInfo['astro2_level'] >= $item['level'])
                    {
                        $gids[] = $gid;
                    }
                    break;
                case 2: // 骰子
                    if ($astrInfo['dice_level'] >= $item['level'])
                    {
                        $gids[] = $gid;
                    }
                    break;
                case 3: // 塔罗
                    if ($astrInfo['tarot_level'] >= $item['level'])
                    {
                        $gids[] = $gid;
                    }
                    break;
                default:
            }
        }

        return $gids;
    }

    /**
     * 获取 问答进行中 状态 描述
     * @param int $astrId
     * @return string
     * @throws \think\Exception
     */
    public function getUnderwayDes(int $astrId)
    {
        if (Cache::get('question_answer:is_underway:' . $astrId, false))
        {
            return '未回复';
        }

        if ($this->alias('t')->join('wechat_backup_07_18_14_43_00.zlcr2_user_add_question q', 'q.qid=t.qid')->where(['t.astr_id' => $astrId, 't.status' => 1, 'q.status' => 2])->count())
        {
            return '有追问';
        }

        return '';
    }
}
